<template>
  <ul class="todo-main">
    <Item
      v-for="todoItem in todoList"
      :key="todoItem.id"
      v-bind="todoItem"
      :changeDoneById="changeDoneById"
      :singleDeleteById="singleDeleteById"
    />
  </ul>
</template>

<script>
import Item from "./Item";

import { v4 as uuidv4 } from "uuid";
import PubSub from "pubsub-js";

export default {
  name: "List",
  components: {
    Item,
  },
  data() {
    return {
      todoList: JSON.parse(localStorage.getItem("todoList") || "[]"),
    };
  },
  methods: {
    changeDoneById(id, done) {
      this.todoList = this.todoList.map((item) => {
        return item.id === id ? { ...item, done } : item;
      });
    },
    singleDeleteById(id) {
      this.todoList = this.todoList.filter((item) => item.id !== id);
    },
  },
  /* 只要 todoList 发生改变我就重新发布 */
  watch: {
    todoList: {
      deep: true,
      handler(newTodoList) {
        /* 发布 todoList */
        this.publishTodoListPSToken = PubSub.publish(
          "setTodoList",
          newTodoList
        );
        /* 存储 localStorage */
        localStorage.setItem("todoList", JSON.stringify(newTodoList))
      },
    },
  },
  mounted() {
    /* 订阅 */
    this.addTodoPSToken = PubSub.subscribe("addTodo", (_, todo) => {
      this.todoList.push(todo);
    });
    this.selectAllPSToken = PubSub.subscribe("selectAll", (_, done) => {
      this.todoList = this.todoList.map((item) => ({ ...item, done }));
    });
    this.deleteCompletedPSToken = PubSub.subscribe("deleteCompleted", () => {
      this.todoList = this.todoList.filter((item) => !item.done);
    });

    /* 发布 */
    this.publishTodoListPSToken = PubSub.publish("setTodoList", this.todoList);
  },
  beforeDestroy() {
    PubSub.unsubscribe(this.addTodoPSToken);
    PubSub.unsubscribe(this.publishTodoListPSToken);
    PubSub.unsubscribe(this.selectAllPSToken);
    PubSub.unsubscribe(this.deleteCompletedPSToken);
  },
};
</script>

<style scoped>
/*main*/
.todo-main {
  margin-left: 0px;
  border: 1px solid #ddd;
  border-radius: 2px;
  padding: 0px;
}

.todo-empty {
  height: 40px;
  line-height: 40px;
  border: 1px solid #ddd;
  border-radius: 2px;
  padding-left: 5px;
  margin-top: 10px;
}
</style>